/**
 * 项目名：化工企业安全生产信息化管理平台
 * 日期：    2020-07-26 17:45:29
 * Copyright (c) 2015- -版权所有
 */

package com.joysuch.wwyt.bp.service.impl;

import java.util.Date;
import java.util.List;

import javax.transaction.Transactional;

import com.joysuch.wwyt.bp.bean.BpDeviceFacilityRepairRecordDetailBean;
import com.joysuch.wwyt.bp.bean.BpDeviceFacilityRepairRecordEditBean;
import com.joysuch.wwyt.bp.bean.BpDeviceFacilityRepairRecordListBean;
import com.joysuch.wwyt.bp.bean.BpDeviceFacilityRepairRecordListBean.SearchBpDeviceFacilityRepairRecord;
import com.joysuch.wwyt.bp.entity.BpDeviceFacilityRepairRecord;
import com.joysuch.wwyt.bp.entity.BpProductionFacility;
import com.joysuch.wwyt.bp.entity.dsl.QBpDeviceFacilityRepairRecord;
import com.joysuch.wwyt.bp.enums.DeviceFacilityRepairStates;
import com.joysuch.wwyt.bp.repository.BpDepartDao;
import com.joysuch.wwyt.bp.repository.BpDeviceFacilityRepairRecordDao;
import com.joysuch.wwyt.bp.repository.BpProductionFacilityDao;
import com.joysuch.wwyt.bp.service.BpDeviceFacilityRepairRecordService;
import com.joysuch.wwyt.core.common.util.PageDataUtils;
import com.joysuch.wwyt.core.common.util.PageDataUtils.PageDataConvert;
import com.joysuch.wwyt.core.exception.BusinessRestrictionsException;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.core.service.BaseAttachmentRepositoryService;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import org.joda.time.LocalDate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

@Service
@Transactional
public class BpDeviceFacilityRepairRecordServiceImpl implements BpDeviceFacilityRepairRecordService {

    @Autowired
    private BpDeviceFacilityRepairRecordDao dao;
    @Autowired
    private BpProductionFacilityDao bpProductionFacilityDao;
    @Autowired
    private BaseUserDao baseUserDao;
    @Autowired
    private BpDepartDao bpDepartDao;
    @Autowired
    private BaseAttachmentRepositoryService baseAttachmentRepositoryService;
    @Autowired
    private BpProductionFacilityDao facilityDao;

    @Override
    public BpDeviceFacilityRepairRecord add(BpDeviceFacilityRepairRecordEditBean entity) {
        BpDeviceFacilityRepairRecord content = new BpDeviceFacilityRepairRecord();
        BeanUtils.copyProperties(entity, content, "id");
        if (entity.getAttachment() != null) {
            content.setAttachmentId(entity.getAttachment().getId());
        }
        //维修金额
        BpProductionFacility facility = facilityDao.findById(entity.getDeviceFacilityId()).orElseThrow(() -> new IllegalArgumentException("设备设施不存在"));
        if (entity.getRepairAmount() == null) {
            entity.setRepairAmount(0.0);
            content.setRepairAmount(0.0);
        }
        if (facility.getRepairAmount() == null) {
            facility.setRepairAmount(entity.getRepairAmount());
        } else {
            facility.setRepairAmount(facility.getRepairAmount() + entity.getRepairAmount());
        }
        facilityDao.save(facility);
        dao.save(content);
//        checkDeviceRepairingState(content);
        this.saveDeviceRepairingState(facility.getId());
        return content;
    }

    private void saveDeviceRepairingState(Long facilityId) {
        BpProductionFacility facility = facilityDao.findById(facilityId).orElseThrow(() -> new IllegalArgumentException("设备设施不存在"));
        int count = dao.countByDeviceFacilityIdAndNowDate(facilityId, new Date());
        if (count > 0) {
            facility.setRepairState(DeviceFacilityRepairStates.REPAIRING.getId());
        } else {
            facility.setRepairState(DeviceFacilityRepairStates.OK.getId());
        }
        facilityDao.save(facility);
    }

//    //true 维修中  false 维修完成
//    private boolean checkDeviceRepairingState(Long deviceFacilityId) {
//        List<BpDeviceFacilityRepairRecord> recordList = dao.findByDeviceFacilityId(deviceFacilityId);
//        if (!CollectionUtils.isEmpty(recordList)) {
//            for (BpDeviceFacilityRepairRecord record : recordList) {
//                boolean b = checkDate(record.getRepairStartDate(), record.getRepairEndDate());
//                if (b) {
//                    return true;
//                }
//            }
//        }
//        return false;
//    }
//
//    //true 维修中  false 维修完成
//    private boolean checkDate(Date startDate, Date endDate) {
//        Date now = LocalDate.now().toDate();
//        return (now.compareTo(startDate) >= 0 && now.compareTo(endDate) <= 0);
//    }

//    private void checkDeviceRepairingState(BpDeviceFacilityRepairRecord content) {
//        Date now = LocalDate.now().toDate();
//        if (now.compareTo(content.getRepairStartDate()) >= 0 && now.compareTo(content.getRepairEndDate()) <= 0) {
//            bpProductionFacilityDao.updateReapairState(content.getDeviceFacilityId(),
//                    DeviceFacilityRepairStates.REPAIRING.getId());
//        } else {
//            bpProductionFacilityDao.updateReapairState(content.getDeviceFacilityId(),
//                    DeviceFacilityRepairStates.OK.getId());
//        }
//    }

    @Override
    public void update(BpDeviceFacilityRepairRecordEditBean entity) {
        BpDeviceFacilityRepairRecord content = dao.findById(entity.getId()).get();
        BeanUtils.copyProperties(entity, content, "id");
        if (entity.getAttachment() != null) {
            content.setAttachmentId(entity.getAttachment().getId());
        } else {
            content.setAttachmentId(null);
        }
        dao.save(content);
        //更新设备维修维修
        this.saveDeviceRepairingState(entity.getDeviceFacilityId());
    }

    /**
     * 删除
     *
     * @param recordId
     */
    @Override
    public void deleteById(Long recordId) {
        BpDeviceFacilityRepairRecord record = dao.findById(recordId).orElseThrow(() -> new IllegalArgumentException("记录不存在"));
        dao.deleteById(recordId);
        //更新设备维修状态
        this.saveDeviceRepairingState(record.getDeviceFacilityId());
    }

    @Override
    public Page<BpDeviceFacilityRepairRecordListBean> findByPage(Pageable page,
                                                                 SearchBpDeviceFacilityRepairRecord condition) {
        Predicate predicate = prepareListSearchCondition(condition);

        Page<BpDeviceFacilityRepairRecord> data = predicate == null ? dao.findAll(page) : dao.findAll(predicate, page);

        return PageDataUtils.convertPageData(data,
                new PageDataConvert<BpDeviceFacilityRepairRecordListBean, BpDeviceFacilityRepairRecord>() {

                    @Override
                    public BpDeviceFacilityRepairRecordListBean convert(BpDeviceFacilityRepairRecord f) {
                        BpDeviceFacilityRepairRecordListBean bean = new BpDeviceFacilityRepairRecordListBean();
                        BeanUtils.copyProperties(f, bean);
                        if (f.getRepairDepartId() != null) {
                            bean.setRepairDepartName(bpDepartDao.findDepartNameById(f.getRepairDepartId()));
                        }
                        if (f.getRepairUserId() != null) {
                            bean.setRepairUserName(baseUserDao.getBaseUserNameById(f.getRepairUserId()));
                        }
                        if (f.getRepairRelatedSafetyJobIds() != null) {
                            // 暂不实现
                        }
                        if (f.getRepairAmount() == null) {
                            bean.setRepairAmount(0 + ".00");
                        } else {
                            String s = String.format("%.2f", f.getRepairAmount());
                            bean.setRepairAmount(s);
                        }
                        return bean;
                    }

                });
    }

    private Predicate prepareListSearchCondition(SearchBpDeviceFacilityRepairRecord condition) {
        Predicate p = null;
        QBpDeviceFacilityRepairRecord q = QBpDeviceFacilityRepairRecord.bpDeviceFacilityRepairRecord;
        if (condition.getRepairUserId() != null) {
            p = ExpressionUtils.and(p, q.repairUserId.eq(condition.getRepairUserId()));
        }
        if (condition.getRepairDepartId() != null) {
            p = ExpressionUtils.and(p, q.repairDepartId.eq(condition.getRepairDepartId()));
        }
        if (condition.getRegisterTime() != null) {
            p = ExpressionUtils.and(p, q.registerTime.eq(condition.getRegisterTime()));
        }
        if (condition.getDeviceFacilityId() != null) {
            p = ExpressionUtils.and(p, q.deviceFacilityId.eq(condition.getDeviceFacilityId()));
        }
        return p;
    }

    @Override
    public void delete(Long id) throws BusinessRestrictionsException {
        // 校验业务逻辑是否允许删除。如本数据被其他业务关联，删除后导致其他业务不可用。不能删除时将抛出业务异常
        checkBussinessRestrictions(id);
        dao.deleteById(id);
    }

    /**
     * 校验业务逻辑是否允许删除。如本数据被其他业务关联，删除后导致其他业务不可用
     *
     * @param id 要删除的业务ID
     * @throws BusinessRestrictionsException 抛出的业务异常
     */
    private void checkBussinessRestrictions(Long id) throws BusinessRestrictionsException {
    }

    @Override
    public BpDeviceFacilityRepairRecord findById(Long id) {
        return dao.findById(id).orElse(null);
    }

    @Override
    public BpDeviceFacilityRepairRecordDetailBean getById(Long id) {
        BpDeviceFacilityRepairRecord f = findById(id);
        if (f == null) {
            return null;
        }
        BpDeviceFacilityRepairRecordDetailBean bean = new BpDeviceFacilityRepairRecordDetailBean();
        BeanUtils.copyProperties(f, bean);
        if (f.getAttachmentId() != null) {
            bean.setAttachment(baseAttachmentRepositoryService.findByIdIntoBean(f.getAttachmentId()));
        }
        if (f.getRepairDepartId() != null) {
            bean.setRepairDepartName(bpDepartDao.findDepartNameById(f.getRepairDepartId()));
        }
        if (f.getRepairUserId() != null) {
            bean.setRepairUserName(baseUserDao.getBaseUserNameById(f.getRepairUserId()));
        }
        if (f.getRegisterUserId() != null) {
            bean.setRegisterUserName(baseUserDao.getBaseUserNameById(f.getRegisterUserId()));
        }
        if (f.getRepairRelatedSafetyJobIds() != null) {
            // 暂不实现
        }
        bean.setRepairAmount(f.getRepairAmount());
        return bean;
    }

}
